package com.service.web;

import java.io.Serializable;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.faces.application.FacesMessage;
import javax.faces.application.NavigationCase;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;

import org.primefaces.model.TreeNode;
import org.primefaces.model.CheckboxTreeNode;

import com.service.module.Module;
import com.service.module.ModuleStruct;

@ManagedBean(name = "treeModuleBean")
@RequestScoped
public class TreeModuleBean implements Serializable {

	private static final long serialVersionUID = 1L;

	private TreeNode modules;

	private TreeNode[] selectedNodes;

	public TreeModuleBean() {
		try {
			ContextoBean contextoBean = ContextoUtil.getContextoBean();
			List<Module> listModules = contextoBean.getListModules();
			modules = new CheckboxTreeNode(new ModuleStruct(0, "Menu"), null);
			for (Module module : listModules) {
				TreeNode node = new CheckboxTreeNode(new ModuleStruct(
						module.getModuleID(), module.getName()), modules);
				List<Module> subModule2 = module.getSubModule();
				for (int i = 0; i < subModule2.size(); i++) {
					Module subModule = subModule2.get(i);
					@SuppressWarnings("unused")
					TreeNode subNode = new CheckboxTreeNode(new ModuleStruct(
							subModule.getModuleID(), subModule.getName()), node);
				}
			}
		} catch (Throwable e) {
			Logger.getLogger(NavigationCase.class.getName()).log(Level.SEVERE,
					null, e);
		}
	}

	public TreeNode getModules() {
		return modules;
	}

	public void setModules(TreeNode modules) {
		this.modules = modules;
	}

	public TreeNode[] getSelectedNodes() {
		return selectedNodes;
	}

	public void setSelectedNodes(TreeNode[] selectedNodes) {
		this.selectedNodes = selectedNodes;
	}

	public void displaySelectedMultiple() {
		if (selectedNodes != null && selectedNodes.length > 0) {
			StringBuilder builder = new StringBuilder();

			for (TreeNode node : selectedNodes) {
				ModuleStruct moduleStruct = (ModuleStruct)node.getData();
				builder.append(moduleStruct.getName() + " - " + moduleStruct.getModuleID());
				builder.append("<br />");
			}

			FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO,
					"Selected", builder.toString());

			FacesContext.getCurrentInstance().addMessage(null, message);
		}
	}
}
